package test.jsp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 使用 JSP 生成静态页面测试
 * 
 * @author hemj
 * @date 2017年1月12日
 */
@Controller
@RequestMapping("/html")
public class JspHtml {

	private static final Logger logger = LoggerFactory.getLogger(JspHtml.class);

	@RequestMapping("/hello")
	public String helloJsp() {
		return "hello";
	}

	@RequestMapping("/create")
	public String createHtml(HttpServletRequest req) {
		InputStream in = null;
		FileOutputStream fos = null;
		try {
			String path = req.getContextPath() + "/html/hello";
			logger.debug("path: {}", path);
			// 请求页面
			URL url = new java.net.URL("http://127.0.0.1:8080" + path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("User-Agent", "Mozilla/4.0");
			conn.connect();
			int code = conn.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				in = new BufferedInputStream(conn.getInputStream());
				// 创建文件
				File outdir = new File(req.getServletContext().getRealPath("/static"));
				if (!outdir.exists()) {
					outdir.mkdirs();
				}
				File file = new File(outdir, "/hello.html");
				fos = new FileOutputStream(file);
				// 输出内容
				byte[] buf = new byte[4096];
				int len = 0;
				while ((len = in.read(buf)) != -1) {
					fos.write(buf, 0, len);
				}
			} else {
				logger.warn("读取页面失败#code-" + code);
			}
		} catch (Exception e) {
			logger.error("生成静态页面异常", e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
				}
			}
		}
		return "redirect:/static/hello.html";
	}
}
